<template>
  <div class="add-member-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">{{ showDepartmentSelect ? '选择部门' : '添加成员' }}</div>
        <div v-if="!showDepartmentSelect" class="header-action" @click="handleComplete">完成</div>
      </div>
    </div>

    <!-- 部门选择界面 -->
    <div v-if="showDepartmentSelect" class="department-select">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" color="#1989fa">加载中...</van-loading>
      </div>
      
      <!-- 部门列表 -->
      <div v-if="!loading" class="department-list">
        <div 
          v-for="department in departments"
          :key="department.id"
          class="department-item"
          @click="selectDepartment(department)"
        >
          <div class="department-icon">
            <img src="@/assets/homeOther/organizational_icon.png" alt="部门" />
          </div>
          <div class="department-info">
            <div class="department-name">
              <!-- {{ department.name }}({{ department.num }}) -->
              {{ department.name }}
            </div>
          </div>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div>
    </div>

    <!-- 成员列表界面 -->
    <div v-else>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" color="#1989fa">加载中...</van-loading>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && availableMembers.length === 0" class="empty-container">
        <img src="/src/assets/homeOther/empty.png" alt="暂无可添加的成员" class="empty-image" />
      </div>
      <!-- 成员列表 -->
      <div v-if="!loading && availableMembers.length > 0" class="member-list">
      <div 
        v-for="member in availableMembers"
        :key="member.id"
        class="member-item"
        @click="toggleMember(member)"
      >
        <div class="member-avatar">
          <AvatarDisplay :url="member.url" :name="member.name" />
        </div>
        <div class="member-info">
          <div class="member-name">
            {{ member.name }}
            <span v-if="member.ceo === 1" class="manager-tag">CEO</span>
            <span v-if="member.admin === 1" class="manager-tag">管理员</span>
            <span v-if="member.hr === 1" class="manager-tag">HR</span>
          </div>
          <div class="member-position">{{ member.position }}</div>
          <!-- <div class="member-phone">{{ member.phone }}</div> -->
        </div>
        <div class="member-action">
          <div 
            class="add-btn" 
            :class="{ selected: selectedMembers.includes(member.id) }"
          >
            {{ selectedMembers.includes(member.id) ? '已选' : '添加' }}
          </div>
        </div>
      </div>
      </div>
    </div>

    <!-- 职位输入对话框 -->
    <van-dialog 
      v-model:show="showPositionDialog" 
      title="输入职位" 
      show-cancel-button
      @confirm="confirmPosition"
      @cancel="cancelPosition"
    >
      <div style="padding: 20px;">
        <van-field
          v-model="inputPosition"
          placeholder="请输入职位"
          clearable
          autocomplete="off"
        />
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { getNoDepartmentMembers, addMember, getAllDepartments, type NoDepartmentMember, type AddMemberResponse, type Department, type AddMemberRequest } from '@/api/organization'
import { getUserPicture } from '@/api/contract'
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue'
import defaultAvatar from '@/assets/homeOther/picture.png'
import { smartGoBack } from '@/utils/navigation'

// 路由实例
const router = useRouter()
const route = useRoute()

// 成员数据类型（适配前端显示需求）
interface Member {
  id: number
  name: string
  phone: string
  position: string
  avatar: string
  url: string // 原始头像URL用于头像组件
  admin: number
  department: number
  ceo: number
  hr: number
}

// 可添加的成员列表
const availableMembers = ref<Member[]>([])

// 已选择的成员ID列表
const selectedMembers = ref<number[]>([])

// 职位输入对话框相关
const showPositionDialog = ref(false)
const currentMember = ref<Member | null>(null)
const inputPosition = ref('')

// 来源页面（从路由参数获取）
const fromPage = ref<string>('')
const departmentId = ref<string>('')

// 加载状态
const loading = ref(false) // 初始为false，避免闪烁

// 返回上一页
const goBack = () => {
  smartGoBack(router)
}

// 部门选择相关
const showDepartmentSelect = ref(false)
const departments = ref<Department[]>([])

// 获取用户头像
const getUserAvatar = async (url: string): Promise<string> => {
  if (!url || url.trim() === '') {
    return defaultAvatar
  }
  
  try {
    const avatarBlob = await getUserPicture(url)
    return URL.createObjectURL(avatarBlob)
  } catch (error) {
    console.error('获取用户头像失败:', error)
    return defaultAvatar
  }
}

// 获取部门数据
const fetchDepartments = async () => {
  try {
    loading.value = true
    const response = await getAllDepartments()
    if (response.code === 0) {
      departments.value = response.data.departments
      console.log('部门数据加载成功:', response.data.departments)
    } else {
      showToast(response.msg || '获取部门数据失败')
    }
  } catch (error) {
    console.error('获取部门数据失败:', error)
    showToast('获取部门数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 选择部门
const selectDepartment = (department: Department) => {
  departmentId.value = department.id.toString()
  showDepartmentSelect.value = false
  // 选择部门后获取无部门成员数据
  fetchNoDepartmentMembers()
}

// 获取无部门成员数据
const fetchNoDepartmentMembers = async () => {
  try {
    loading.value = true
    const response = await getNoDepartmentMembers()
    if (response.code === 0) {
      // 处理成员数据，获取头像
      const membersWithAvatars = await Promise.all(
        response.data.map(async (member: NoDepartmentMember) => {
          const avatar = await getUserAvatar(member.url)
          return {
            id: member.id,
            name: member.name,
            phone: member.phone,
            position: member.position,
            avatar: avatar,
            url: member.url, // 保留原始URL用于头像组件
            admin: member.admin,
            department: member.department,
            ceo: member.ceo,
            hr: member.hr
          }
        })
      )
      
      availableMembers.value = membersWithAvatars
      console.log('无部门成员数据加载成功:', response.data)
    } else {
      showToast(response.msg || '获取无部门成员失败')
    }
  } catch (error) {
    console.error('获取无部门成员失败:', error)
    showToast('获取无部门成员失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 切换成员选择状态
const toggleMember = (member: Member) => {
  const index = selectedMembers.value.indexOf(member.id)
  if (index > -1) {
    // 取消选择
    selectedMembers.value.splice(index, 1)
  } else {
    // 检查职位是否为空
    if (!member.position || member.position.trim() === '') {
      // 职位为空，弹出输入框
      currentMember.value = member
      inputPosition.value = ''
      showPositionDialog.value = true
    } else {
      // 职位不为空，直接添加
      selectedMembers.value.push(member.id)
    }
  }
}

// 确认输入职位
const confirmPosition = () => {
  if (!inputPosition.value.trim()) {
    showToast('请输入职位')
    return
  }
  
  if (currentMember.value) {
    // 更新成员职位信息
    const memberIndex = availableMembers.value.findIndex(m => m.id === currentMember.value!.id)
    if (memberIndex !== -1) {
      availableMembers.value[memberIndex].position = inputPosition.value.trim()
    }
    
    // 添加到选中列表
    selectedMembers.value.push(currentMember.value.id)
    
    // 关闭对话框
    showPositionDialog.value = false
    currentMember.value = null
    inputPosition.value = ''
  }
}

// 取消输入职位
const cancelPosition = () => {
  showPositionDialog.value = false
  currentMember.value = null
  inputPosition.value = ''
}

// 完成添加
const handleComplete = async () => {
  if (selectedMembers.value.length === 0) {
    showToast('请选择要添加的成员')
    return
  }

  // 检查部门ID是否存在
  if (!departmentId.value) {
    showToast('部门信息缺失，无法添加成员')
    return
  }

  try {
    loading.value = true
    
    // 构建成员数据数组，包含部门ID、成员ID和职位信息
    const membersData: AddMemberRequest[] = selectedMembers.value.map(memberId => {
      const member = availableMembers.value.find(m => m.id === memberId)
      return {
        id: departmentId.value,
        memberId: memberId.toString(),
        position: member?.position || '测试' // 使用成员现有职位或默认职位
      }
    })
    
    // 调用添加成员接口
    const response = await addMember(membersData)
    
    if (response.code === 0) {
      showToast('添加成员成功')
      
      // 根据来源页面返回对应页面
      if (fromPage.value === 'department' && departmentId.value) {
        router.push(`/organization/department/${departmentId.value}`)
      } else {
        router.push('/organization')
      }
    } else {
      showToast(response.msg || '添加成员失败')
    }
  } catch (error) {
    console.error('添加成员失败:', error)
    showToast('添加成员失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  // 优化加载体验：延迟显示loading，避免闪烁
  let loadingTimer: NodeJS.Timeout | null = null;
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    loading.value = true;
  }, 200);
  
  // 获取路由参数
  fromPage.value = route.query.from as string || ''
  departmentId.value = route.query.departmentId as string || ''
  
  console.log('页面参数:', { from: fromPage.value, departmentId: departmentId.value })
  console.log(departments.value,'-departments');
  
  // 数据加载完成后清除定时器
  const clearLoadingTimer = () => {
    if (loadingTimer) {
      clearTimeout(loadingTimer);
      loadingTimer = null;
    }
    loading.value = false;
  };
  
  // 如果是从根组织进入，显示部门选择
  if (fromPage.value === 'root' || !departmentId.value) {
    showDepartmentSelect.value = true
    fetchDepartments().finally(clearLoadingTimer)
  } else {
    // 如果是从部门进入，直接获取无部门成员数据
    fetchNoDepartmentMembers().finally(clearLoadingTimer)
  }
})
</script>

<style lang="scss" scoped>
@import url('./style/add-member.scss');
</style>